//
//  ViewController.swift
//  HDSearchDemo
//
//  Created by HD-XXZQ-iMac on 2018/1/30.
//  Copyright © 2018年 HD-XXZQ-iMac. All rights reserved.
//

import UIKit


class ViewController: UIViewController {
    
    
    var dataSource = [String]()
    var tableview : UITableView?
    var searchVC : UISearchController?
    var searchResultVC: SearchTableViewController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initialData()
        setupUI()
    }

    func initialData() {
        let jsonPath: String? = Bundle.main.path(forResource: "PersonList", ofType: ".json")
        let url = URL.init(fileURLWithPath: jsonPath!)
        let jsonData = NSData.init(contentsOf: url)
        let jsonStr = String.init(data: jsonData! as Data, encoding: String.Encoding.utf8)
        
        if let model = DataModel.deserialize(from: jsonStr) {
            print(model.data)
            dataSource = model.data
        }
        
        for i in 0..<dataSource.count { //
            autoreleasepool {
                let name: String = dataSource[i]
                WPFPinYinDataManager.addInitializeString(name, identifer: "\(i)")
            }
        }
    }

    func setupUI() {
        
        tableview = UITableView.init(frame: self.view.bounds, style: UITableViewStyle.plain)
        tableview?.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableview?.delegate = self
        tableview?.dataSource = self
        tableview?.rowHeight = 50
        self.view.addSubview(self.tableview!)
        
        searchResultVC = SearchTableViewController.init(style: UITableViewStyle.plain)
        searchVC = UISearchController.init(searchResultsController: searchResultVC)
        searchVC?.hidesNavigationBarDuringPresentation = true  // 开始输入时，是否隐藏导航栏
        searchVC?.dimsBackgroundDuringPresentation = true    // 是否出现背景色
        searchVC?.definesPresentationContext = true
        searchVC?.searchResultsUpdater = self
        searchVC?.searchBar.delegate = self
        searchVC?.delegate = self
//        self.navigationItem.titleView = self.searchVC?.searchBar
        self.tableview?.tableHeaderView = self.searchVC?.searchBar
    }

}

extension ViewController: UITableViewDataSource,UITableViewDelegate {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "cell")!
        cell.textLabel?.text = self.dataSource[indexPath.row]
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
}

extension ViewController: UISearchBarDelegate {
    func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
        searchVC?.searchBar.showsCancelButton = true
        return true
    }
    
    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        
    }
}

extension ViewController: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {
        let keyword: String = (searchController.searchBar.text?.lowercased())!
        print(keyword as Any)
        if keyword.count < 1 {
            return
        }
        let beginTime = Date()
        print("开始匹配，开始时间：\(beginTime)")
        var resultDataSource = [WPFPerson]()
        var modelArray = [WPFPerson]()
        modelArray =  WPFPinYinDataManager.getInitializedDataSource() as! [WPFPerson]
        modelArray.forEach { (person) in
            let resultModel = WPFPinYinTools.searchEffectiveResult(withSearch: keyword, person: person)
            if resultModel != nil {
                person.highlightLoaction = (resultModel?.highlightedRange.location)!
                person.textRange = (resultModel?.highlightedRange)!
                person.matchType = Int((resultModel?.matchType)!.rawValue)
                resultDataSource.append(person)
            }
        }
        searchResultVC?.resultDataArr = resultDataSource
        var mutableResultDataArr = NSMutableArray.init(array: (searchResultVC?.resultDataArr)!)
        let rule : [NSSortDescriptor] = WPFPinYinTools.sortingRules() as! [NSSortDescriptor]
        
        mutableResultDataArr.sort(using: rule)
        searchResultVC?.resultDataArr = mutableResultDataArr as! [WPFPerson]
        let endTime = Date()
        let costTime: TimeInterval = endTime.timeIntervalSince(beginTime)
        print("匹配结束，结束时间：\(endTime)，耗时：\(costTime)")
        DispatchQueue.main.async {
            self.searchResultVC?.tableView.reloadData()
        }
        
    }
}

extension ViewController: UISearchControllerDelegate {
    func willPresentSearchController(_ searchController: UISearchController) {
        let resultTableView = searchResultVC?.tableView
        resultTableView?.frame.origin.y = UIApplication.shared.statusBarFrame.size.height + (self.navigationController?.navigationBar.frame.size.height)!
        resultTableView?.frame.size.height = UIScreen.main.bounds.size.height - (resultTableView?.frame.origin.y)!
    }
    
}
